package com.unis.service.system.impl;

import java.util.List;
import java.util.Map;

import com.unis.common.constant.Constants;
import com.unis.dto.ResultDto;
import com.unis.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.mapper.system.DepartmentMapper;
import com.unis.model.system.Department;
import com.unis.service.system.DepartmentService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see DepartmentService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2018-12-27
 */
@Service("departmentService")
public class DepartmentServiceImpl extends BaseServiceImpl implements DepartmentService {
	private static final Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    @Autowired
    private DepartmentMapper departmentMapper;

	@Autowired
	private CacheManager cacheManager;

    /**
     * @see DepartmentService#insert(Department department)
     */
    @Override
    public int insert(Department department) throws Exception {
    	if (department!=null){
	        //department.setPk(TemplateUtil.genUUID());
	                
	        return departmentMapper.insert(department);
    	}else{
    		logger.error("DepartmentServiceImpl.insert时department数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.insert时department数据为空。");
    	}        
    }

    /**
     * @see DepartmentService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("DepartmentServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.delete时pk为空。");
    	}else{
    		return departmentMapper.deleteByPrimaryKey(pk);
    	}
    }

    /**
     * @see DepartmentService#updateByPrimaryKey(Department department)
     */
    @Override
    public int updateByPrimaryKey(Department department) throws Exception {
        if (department!=null){
        	if(StringUtils.isBlank(department.getPk())){
        		logger.error("DepartmentServiceImpl.updateByPrimaryKey时department.Pk为空。");
        		throw new AppRuntimeException("DepartmentServiceImpl.updateByPrimaryKey时department.Pk为空。");
        	}
	        return departmentMapper.updateByPrimaryKeySelective(department);
    	}else{
    		logger.error("DepartmentServiceImpl.updateByPrimaryKey时department数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.updateByPrimaryKey时department数据为空。");
    	}
    }
    /**
     * @see DepartmentService#queryDepartmentByPrimaryKey(String pk)
     */
    @Override
    public Department queryDepartmentByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("DepartmentServiceImpl.queryDepartmentByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.queryDepartmentByPrimaryKey时pk为空。");
    	}else{
    		return departmentMapper.selectByPrimaryKey(pk);
    	}
    }
    
    
    /**
     * @see DepartmentService#queryAsObject(Department department)
     */
    @Override
    public Department queryAsObject(Department department) throws Exception {
        if (department!=null){
	        return departmentMapper.selectOne(department);
    	}else{
    		logger.error("DepartmentServiceImpl.queryAsObject时department数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.queryAsObject时department数据为空。");
    	}
    }
    
    /**
     * @see DepartmentService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return departmentMapper.selectCountByExample(example);
    	}else{
    		logger.error("DepartmentServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see DepartmentService#queryListByExample(Example example)
     */
    @Override
    public List<Department> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return departmentMapper.selectByExample(example);
    	}else{
    		logger.error("DepartmentServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see DepartmentService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(departmentMapper.selectByExample(example));
    	}else{
    		logger.error("DepartmentServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("DepartmentServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }

	@Override
	public List<Map<String, Object>> selectTreeList(String sjdm, String filterSql,int deptLevel) {
		List<Map<String,Object>> list = null;
		Cache cache = cacheManager.getCache(Constants.ENCACHE_POOL);
		list = cache.get("all"+"_"+(StringUtils.isNotBlank(sjdm)?sjdm : deptLevel)+(StringUtils.isNotBlank(filterSql)?"_"+filterSql:""),List.class);
		if (list==null || list.size()==0){
			list = departmentMapper.selectTreeList(sjdm,filterSql);//上级代码为空时，默认条件为codeLevel = 1
			if (list!=null && list.size()>0){
				for(Map<String,Object> map : list){
					if (map.get("isparent")!=null && StringUtils.isNotBlank(map.get("isparent").toString())&& StringUtils.equalsIgnoreCase("true",map.get("isparent").toString())){
						map.put("nodes",this.selectTreeList(map.get("dm").toString(),filterSql,0));
					}
				}
			}
			cache.put("all"+"_"+(StringUtils.isNotBlank(sjdm)?sjdm : deptLevel)+(StringUtils.isNotBlank(filterSql)?"_"+filterSql:""),list);
		}

		return  list;
	}
	/**
	 * @see DepartmentService#queryListByPage(Map, int, int)
	 */
	@Override
	public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
		if (parmMap!=null){
			Example example = new Example(Department.class);
			example.setOrderByClause("deptcode asc");//设置排序
			Example.Criteria criteria = example.createCriteria();
			//criteria设置
			// = --> andEqualTo(field,value)
			// like --> andLike(field,likeValue)；likeValue 包含‘%’
			// is null --> andIsNull(field)
			// is not null --> andIsNotNull(field)
			// <> --> andNotEqualTo(field)
			// > --> andGreaterThan(field,value)
			// >= --> andGreaterThanOrEqualTo(field,value)
			// < --> andLessThan(field,value)
			// <= --> andLessThanOrEqualTo(field,value)
			// in --> andIn(field,Iterable value)
			// not in --> andNotIn(field,Iterable value)
			// between --> andBetween(field,beginValue,endValue)
			// not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

			// or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

			//criteria.andEqualTo("yxx",1);设置yxx=1
			/**
			 *此方法请根据需要修改下方条件
			 */
			//此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
			//生成条件中均为 and field = value
			//生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改
			if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
			}
			if(parmMap.get("deptcode")!=null && StringUtils.isNotBlank(parmMap.get("deptcode").toString())){
				criteria.andLike("deptcode",parmMap.get("deptcode").toString().trim()+"%");
			}
			if(parmMap.get("name")!=null && StringUtils.isNotBlank(parmMap.get("name").toString())){
				criteria.andLike("name","%"+parmMap.get("name").toString().trim()+"%");
			}
			if(parmMap.get("parent")!=null && StringUtils.isNotBlank(parmMap.get("parent").toString())){
				criteria.andLike("parent",parmMap.get("parent").toString().trim()+"%");
			}
			if(parmMap.get("deptLevel")!=null && StringUtils.isNotBlank(parmMap.get("deptLevel").toString())){
				criteria.andEqualTo("deptLevel",parmMap.get("deptLevel").toString().trim());
			}
			PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			//result.setTotal(pageInfo.getPages());
			result.setTotal((int)pageInfo.getTotal());
			return result;
		}else{
			logger.error("DeptServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("DeptServiceImpl.queryListByPage时parmMap数据为空。");
		}
	}

}
